package com.frontop.bigdata.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author YangBoos
 * @title: BaiduDataUtil
 * @projectName frontop-cloud
 * @description: 百度数据获取工具
 * @date 2022/2/11 16:53
 */
public class BaiduDataUtil {

    public static JSONObject requestBaidu(JSONObject bodyJson){
        //定义json参数
        JSONObject prameter = new JSONObject();

        //设置必填认证参数
        JSONObject header = new JSONObject();
        header.put("username","testaka");
        header.put("password","@Test1313");
        header.put("token","67bba0b8392294782bd893c6edbbc6f1");
        header.put("account_type",1);
        String url = "";
        //设置参数
        prameter.put("header",header);
        if(bodyJson != null){
            url = "https://api.baidu.com/json/tongji/v1/ReportService/getData";
            prameter.put("body",bodyJson);
        }else {
            url = "https://api.baidu.com/json/tongji/v1/ReportService/getSiteList";
        }

        OkHttpClient client = new OkHttpClient().newBuilder() //
                .readTimeout(60, TimeUnit.SECONDS) // 设置读取超时时间
                .writeTimeout(60, TimeUnit.SECONDS) // 设置写的超时时间
                .connectTimeout(60, TimeUnit.SECONDS) // 设置连接超时时间
                .build();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON,prameter.toJSONString());

        Request request = new Request
                .Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return JSONObject.parseObject(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
